// components/calendar/calendar.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    lastMonth: {
      type: String,
      value: '◀'
    },
    nextMonth: {
      type: String,
      value: '▶'
    },
    weekText: {
      type: Array,
      value: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    title: '2021年06月',
    emptyGridsBefore: [], //装上个月
    thisMonthDays: [], //本月
    emptyGridsAfter: [] //下月
  },

  /**
   * 组件的方法列表
   */
  methods: {
    today() {
      // 默认选中当天，并初始化组件
      let Year = new Date().getFullYear()
      let Month = new Date().getMonth() + 1
      Month < 10 ? Month = '0' + Month : null
      let Day = new Date().getDate()
      // 格式化输出
      let select = `${Year}-${Month}-${Day}`;

      Month = 12
      // 初始化日历组件
      this.display(Year, Month, Day)
    },
    display(year, month, date) {
      this.setData({
        title: `${year}年${month}月`
      })

      this.createDays(year, month)
    },
    // 绘制当月天数占格
    createDays(year, month) {
      let thisMonthDays = [],
        days = new Date(year, month, 0).getDate()
        console.log(beforeDays);
      for (let i = 1; i <= days; i++) {
        thisMonthDays.push(i)
      }


      let emptyGridsBefore = [],
        beforeDays = new Date(year, month - 1, 1).getDay()

      let lastMonthDays = new Date(month - 1 >= 0 ? year : year - 1, month - 1 >= 0 ? month - 1 : 11, 0).getDate()
      for (let i = 1; i <= beforeDays; i++) {
        emptyGridsBefore.unshift(lastMonthDays - i + 1)
      }



      let emptyGridsAfter = [],
        afterDays = 7 - new Date(year, month - 1, days).getDay()
      console.log(afterDays);

      for (let i = 1; i <= afterDays; i++) {
        emptyGridsAfter.push(i)
      }


      this.setData({
        thisMonthDays,
        emptyGridsBefore,
        emptyGridsAfter
      })
    },
    lastMonth() {
      let year = this.data.title.substr(0, 4)
      let month = this.data.title.substr(5, 2)


      if (month - 1 <= 0) {
        year--;
        month = 12
      } else {
        month--
      }

      month = this.zero(month)


      this.display(year, month)

      this.setData({
        title: `${year}年${month}月`
      })
      console.log(this.data.title);
    },
    zero(month) {
      return month < 10 ? '0' + month : month
    }
  },

  ready: function () {
    this.today()
  }
})